/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: HandleFillVo.java
 * Author:   15050536
 * Date:     2016年12月7日 上午9:16:24
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.service.impl.tm;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suning.sawp.constants.TMCategoryEnum;
import com.suning.sawp.constants.TMConstants;
import com.suning.sawp.intf.tm.vo.AllSaleInfoVo;
import com.suning.sawp.intf.tm.vo.CategoryInfoVo;
import com.suning.sawp.intf.tm.vo.EmployeeHireInfoVo;
import com.suning.sawp.intf.tm.vo.ExpensiveSaleVo;
import com.suning.sawp.intf.tm.vo.FirstSaleInfoVo;
import com.suning.sawp.intf.tm.vo.MemberInfoVo;
import com.suning.sawp.intf.tm.vo.ThisYearSaleInfoVo;
import com.suning.sawp.intf.tm.vo.TotalSaleInfoVo;
import com.suning.sawp.intf.tm.vo.TypePercentVo;
import com.suning.sawp.po.tm.EmployeeCategoryInfo;
import com.suning.sawp.po.tm.EmployeeExpensiveSaleInfo;
import com.suning.sawp.po.tm.EmployeeFirstSaleInfo;
import com.suning.sawp.po.tm.EmployeeHireInfo;
import com.suning.sawp.po.tm.EmployeeMemberInfo;
import com.suning.sawp.po.tm.EmployeeTotalSaleInfo;
import com.suning.sawp.service.util.NumberUtils;

/**
 * 时光机-将库中查询出的数据，组装成前端需要的vo对象
 *
 * @author 15050536 石键平
 */
public class HandleFillVo {
	/**
	 * 日志信息
	 */
	private Logger LOGGER = LoggerFactory.getLogger(HandleFillVo.class);
	/**
	 * joda 时间格式
	 */
	private static DateTimeFormatter format10 = DateTimeFormat.forPattern("yyyy-MM-dd");
	private AtomicInteger i = new AtomicInteger();

	/**
	 * 生成员工入职相关信息vo
	 *
	 * @param employeeHireInfo
	 * @return
	 */
	public EmployeeHireInfoVo fillHireVo(EmployeeHireInfo employeeHireInfo) {
		if (employeeHireInfo == null) {
			return null;
		}
		int totalDay = employeeHireInfo.getHireDay();
		int ranking = employeeHireInfo.getRanking();
		int countAll = employeeHireInfo.getCountAll();
		String totalMonth = String.valueOf(employeeHireInfo.getHireMonth());
		String percent = NumberUtils.calculatePercent(countAll - ranking, countAll);

		EmployeeHireInfoVo hireInfoVo = new EmployeeHireInfoVo(employeeHireInfo.getEmployeeId(), employeeHireInfo.getGender(), String.valueOf(totalDay), employeeHireInfo.getHireTime(), percent,
				employeeHireInfo.getHasGotCoupon(), totalMonth);
		return hireInfoVo;
	}

	/**
	 * 根据库里记录，生成总销售记录信息
	 *
	 * @param firstSale
	 *            首次销售信息
	 * @param totalSale
	 *            总销售信息
	 * @param hireInfo
	 *            员工入职信息
	 * @return
	 */
	public AllSaleInfoVo fillAllSaleInfoVo(EmployeeFirstSaleInfo firstSale, EmployeeTotalSaleInfo totalSale, EmployeeHireInfo hireInfo) {
		if (firstSale == null) {
			return null;
		}
		AllSaleInfoVo allSaleInfo = new AllSaleInfoVo();
		// 首单信息
		FirstSaleInfoVo firstSaleInfoVo = fillFirstSaleInfoVo(firstSale);
		allSaleInfo.setFirst(firstSaleInfoVo);
		// 总信息
		TotalSaleInfoVo totalSaleInfoVo = fillTotalSaleInfoVo(totalSale, hireInfo);
		allSaleInfo.setTotal(totalSaleInfoVo);
		return allSaleInfo;
	}

	/**
	 * 生成首单vo
	 */
	public FirstSaleInfoVo fillFirstSaleInfoVo(EmployeeFirstSaleInfo firstSale) {
		FirstSaleInfoVo firstSaleInfoVo = new FirstSaleInfoVo();
		firstSaleInfoVo.setFirstSaleDate(firstSale.getSaleDate());
		DateTime dt = DateTime.parse(firstSale.getSaleDate(), format10);
		firstSaleInfoVo.setWeekDay(NumberUtils.getWeek(dt.getDayOfWeek()));
		// 付款总金额
		BigDecimal amount = firstSale.getPayAmnt();
		if (amount != null) {
			firstSaleInfoVo.setAmount(amount.toPlainString());
		}
		firstSaleInfoVo.setType(firstSale.getCateCode());
		firstSaleInfoVo.setCmmdtyName(firstSale.getCmmdtyName());
		// 商品数量
		Integer num = firstSale.getNum();
		if (num == null || num == 0) {
			num = 1;
		}
		// 设置单价
		if (firstSale.getPrice() != null) {
			firstSaleInfoVo.setCmmdtyAmount(firstSale.getPrice().toPlainString());
		} else if (amount != null) { // 单价为空的时候，用总价除以数量得到单价
			firstSaleInfoVo.setCmmdtyAmount(NumberUtils.divide(amount, num));
		}
		firstSaleInfoVo.setCmmdtyNum(String.valueOf(num));
		return firstSaleInfoVo;
	}

	/**
	 * 构建总销售记录信息
	 */
	private TotalSaleInfoVo fillTotalSaleInfoVo(EmployeeTotalSaleInfo totalSale, EmployeeHireInfo hireInfo) {
		TotalSaleInfoVo totalSaleInfoVo = new TotalSaleInfoVo();
		BigDecimal amount = totalSale.getAmount();
		totalSaleInfoVo.setAmount(amount.toPlainString());
		// 总订单数
		int orderNum = totalSale.getOrderNum();
		int month = hireInfo.getHireMonth();
		// 计算平均每月多少笔订单
		String orderNumPerMonth = NumberUtils.divide(orderNum, month);
		totalSaleInfoVo.setOrderNumPerMonth(orderNumPerMonth);
		totalSaleInfoVo.setOrderNum(String.valueOf(orderNum));
		// 根据入司时长和销售金额判断销售的情况是好是差
		int saleState = NumberUtils.getSaleState(amount.doubleValue(), hireInfo.getHireTime());
		totalSaleInfoVo.setState(String.valueOf(saleState));
		return totalSaleInfoVo;
	}

	/**
	 * 添加2016年，销售记录信息
	 * 
	 * @param expensiveSale
	 * @param categoryInfo
	 * @param memberInfos
	 * @return
	 */
	public ThisYearSaleInfoVo fillThisYearSaleInfoVo(EmployeeExpensiveSaleInfo expensiveSale, EmployeeCategoryInfo categoryInfo, List<EmployeeMemberInfo> memberInfos) {
		if (expensiveSale == null || CollectionUtils.isEmpty(memberInfos)) {
			return null;
		}
		ThisYearSaleInfoVo thisYearSaleInfoVo = new ThisYearSaleInfoVo();

		ExpensiveSaleVo expensiveSaleVo = fillExpensiveSaleVo(expensiveSale);
		thisYearSaleInfoVo.setMostSale(expensiveSaleVo);

		EmployeeMemberInfo memberInfo = memberInfos.get(0);

		CategoryInfoVo statictisInfo = fillCategoryInfoVo(categoryInfo, memberInfo);
		thisYearSaleInfoVo.setStatictisInfo(statictisInfo);

		List<MemberInfoVo> memberInfoVos = fillMemberInfoVo(memberInfos);
		thisYearSaleInfoVo.setOldCustomer(memberInfoVos);

		String oldCustomerPercent = NumberUtils.calculatePercent(memberInfo.getOldMemberNum(), memberInfo.getMemberNum());
		thisYearSaleInfoVo.setOldCustomerPercent(oldCustomerPercent);

		return thisYearSaleInfoVo;
	}

	/**
	 * 生成2016年最贵的销售记录信息
	 *
	 * @param expensiveSale
	 * @return
	 */
	public ExpensiveSaleVo fillExpensiveSaleVo(EmployeeExpensiveSaleInfo expensiveSale) {
		ExpensiveSaleVo expensiveSaleVo = new ExpensiveSaleVo();
		String type = expensiveSale.getCateCode();
		expensiveSaleVo.setType(type);
		String typeName = StringUtils.EMPTY;

		try {
			String key = "CATE_" + expensiveSale.getCateCode();
			typeName = TMCategoryEnum.valueOf(key).getName();
			expensiveSaleVo.setTypeName(typeName);
		} catch (IllegalArgumentException e) {
			expensiveSaleVo.setTypeName(TMCategoryEnum.CATE_OTHER.getName());
			LOGGER.error("获取类目名称失败,code:{}", expensiveSale.getCateCode(), e);
		}
		expensiveSaleVo.setDate(expensiveSale.getSaleDate());
		expensiveSaleVo.setAmount(expensiveSale.getPayAmnt().toPlainString());
		expensiveSaleVo.setCmmdtyName(expensiveSale.getCmmdtyName());
		Integer num = expensiveSale.getNum();
		if (num == null || num == 0) {
			num = 1;
		}
		expensiveSaleVo.setCmmdtyNum(String.valueOf(num));
		expensiveSaleVo.setCmmdtyAmnt(NumberUtils.divide(expensiveSale.getPayAmnt(), num));
		String customName = expensiveSale.getCustomName();
		String gender = expensiveSale.getGender();
		// 没名字就展示X顾客
		if (StringUtils.isEmpty(customName) || customName.length() > 4) {
			customName = TMConstants.CustomName.X;
		} else {
			// 有名字就根据性别展示 某先生，某女士
			customName = getCustomName(customName, gender);
		}
		expensiveSaleVo.setCustomName(customName);

		return expensiveSaleVo;
	}

	/**
	 * 按品类分组 计算各品类占销售的百分比
	 *
	 * @param categoryInfo
	 * @param memberInfo
	 * @return
	 */

	private CategoryInfoVo fillCategoryInfoVo(EmployeeCategoryInfo categoryInfo, EmployeeMemberInfo memberInfo) {
		CategoryInfoVo categoryInfoVo = new CategoryInfoVo();
		BigDecimal payAmntAll = categoryInfo.getPayAmntAll();
		if (payAmntAll == null) {
			return null;
		}
		List<TypePercentVo> typePercent = new ArrayList<TypePercentVo>();

		// 构造个分类数据
		try {
			for (TMCategoryEnum te : TMCategoryEnum.values()) {
				String code = te.getCode();
				// 00011，00019忽略
				if (TMCategoryEnum.CATE_00011.getCode().equals(code) || TMCategoryEnum.CATE_00019.getCode().equals(code)) {
					continue;
				}

				if (TMCategoryEnum.CATE_OTHER.getCode().equals(code)) {
					code = "Other";
				}
				String methodName = "getPayAmnt" + code;

				Method m = categoryInfo.getClass().getDeclaredMethod(methodName);
				BigDecimal payAmnt = (BigDecimal) m.invoke(categoryInfo);
				// 构造各个分类数据
				setTypePercent(payAmnt, payAmntAll, te, typePercent);
			}
			Collections.sort(typePercent);
		} catch (Exception e) {
			LOGGER.error("获取类别金额数据异常", e);
			return null;
		}

		// 2016总接待人数
		if (memberInfo != null) {
			categoryInfoVo.setCustomerNum(String.valueOf(memberInfo.getMemberNum()));
		}
		categoryInfoVo.setTypePercent(typePercent);
		return categoryInfoVo;
	}

	/**
	 * 
	 * 生成接待老员工信息vo
	 *
	 * @param memberInfos
	 * @return
	 */
	public List<MemberInfoVo> fillMemberInfoVo(List<EmployeeMemberInfo> memberInfos) {
		if (CollectionUtils.isEmpty(memberInfos)) {
			return null;
		}
		List<MemberInfoVo> memberInfoVos = new ArrayList<MemberInfoVo>();
		for (EmployeeMemberInfo memberInfo : memberInfos) {
			MemberInfoVo memberInfoVo = new MemberInfoVo();
			String customName = getCustomName(memberInfo.getCustomName(), memberInfo.getGender());
			memberInfoVo.setName(customName);
			memberInfoVo.setNum(String.valueOf(memberInfo.getOrderNum()));
			memberInfoVo.setAllMemberNum(String.valueOf(memberInfo.getMemberNum()));
			memberInfoVo.setOldMemberNum(String.valueOf(memberInfo.getOldMemberNum()));
			
			memberInfoVos.add(memberInfoVo);
		}
		return memberInfoVos;
	}

	/**
	 * 
	 * 设置类目 百分比
	 *
	 * @param payAmntType
	 * @param payAmntAll
	 * @param categoryEnum
	 * @param typePercent
	 */
	public void setTypePercent(BigDecimal payAmntType, BigDecimal payAmntAll, TMCategoryEnum categoryEnum, List<TypePercentVo> typePercent) {
		if (payAmntType != null && payAmntType.doubleValue() > 0d && payAmntAll != null && payAmntAll.doubleValue() > 0d) {
			TypePercentVo tp = new TypePercentVo();
			tp.setType(categoryEnum.getCode());
			tp.setTypeName(categoryEnum.getName());
			String percent = NumberUtils.calculatePercent(payAmntType, payAmntAll);
			//0.00%就忽略不需要了
			if(TMConstants.EMPTY_PERCENT.equals(percent)){
				return;
			}
			tp.setPercent(percent);
			typePercent.add(tp);
		}
	}

	/**
	 * 
	 * 有姓名就获取个姓名，没有姓名就用默认姓名
	 *
	 * @param memberInfo
	 * @return
	 */
	public String getCustomName(String customName, String gender) {
		String[] customerNames = new String[] { TMConstants.CustomName.A, TMConstants.CustomName.B, TMConstants.CustomName.C, TMConstants.CustomName.D, TMConstants.CustomName.E };
		// 名字为空，或者 长度大于4，都以默认名字来替换 ,或者性别不明的
		if (StringUtils.isBlank(customName) || customName.length() > 4) {
			customName = customerNames[i.getAndIncrement() % 5];
			if (i.get() == 1000) {
				i.set(0);
			}
			return customName;
		}
		customName = customName.trim();

		// 小于或等于4个字的名字，取首字，加后缀
		String suffix = TMConstants.FAMALE.equals(gender) ? "女士" : "先生";
		customName = customName.substring(0, 1) + suffix;

		return customName;
	}

}
